# -*- coding:utf-8 -*-
import csv
from datetime import datetime

import psutil
import wmi
import time
import xlwt

cpu_csv_headers = ['主机名', 'CPU型号', '物理核心数', '逻辑核心数']
cpu_info = []
memory_csv_headers = ['内存厂商', '内存型号', '内存大小']
memory_info = []
netadapter_csv_headers = ['适配器名称', '生产厂商', '设备ID','设备类型', '是否为物理设备', '网络状态', 'MAC地址']
netadapter_info = []
netconnect_csv_headers = ['适配器名称', '是否启动', '当前速率', 'IPv4地址', '子网掩码']
netconnect_info = []
disk_csv_headers = ['硬盘型号', '总容量']
disk_info = []
partitions_csv_header = ['分区挂载点', '文件系统', '总大小', '使用量', '空闲量', '使用比例']
partition_info = []
resource_csv_headers = ['主板生产商', '主板序列号', '主板型号', 'BIOS生产商','BIOS名称' ,'BIOS版本', 'BISO序列号', 'CPU占用率', '内存总大小', '内存可用', '内存占用率', '时间戳']
resource_info = []
ps_csv_headers = ['PID', '进程名', '状态', '创建时间', 'CPU时间', '内容使用率', '开启线程数']
ps_info = []


w = wmi.WMI()
## 主机名


## 主板型号
# for BIOSs in w.Win32_BIOS():
#     cpu_info.append(BIOSs.SerialNumber)

## CPU型号
print('———————————————————— 准备开始获取系统信息')
time.sleep(1.5)
print('开始获取CPU信息')
for processor in w.Win32_Processor():
    cpu_info_sub = []
    for BIOSs in w.Win32_ComputerSystem():
        cpu_info_sub.append(BIOSs.Caption)
    cpu_info_sub.append(processor.Name.strip())
    cpu_info_sub.append(processor.NumberOfCores)
    cpu_info_sub.append(processor.NumberOfLogicalProcessors)
    cpu_info.append(cpu_info_sub)
    print('>', end='')
    time.sleep(0.1)
cpu_csv_headers.append('物理核心总数：%s' % psutil.cpu_count(logical=False))
cpu_csv_headers.append('逻辑核心总数：%s' % psutil.cpu_count())
print('\nCPU信息获取完毕。\n开始获取内存信息')

## 内存
for memModule in w.Win32_PhysicalMemory():
    memory_info_sub = []
    totalMemSize = int(memModule.Capacity)
    memory_info_sub.append(memModule.Manufacturer)
    memory_info_sub.append(memModule.PartNumber.strip())
    memory_info_sub.append(str(totalMemSize / 1024 ** 3) + 'GB')
    memory_info.append(memory_info_sub)
    print('>', end='')
    time.sleep(0.1)
memory_csv_headers.append('内存条总数： %s' % len(memory_info))
print('\n内存信息获取完毕。\n开始获取网卡信息')

## 网卡
for netadpter in w.Win32_NetworkAdapter():
    netadpter_box = []
    name = netadpter.Name.strip()
    netadpter_box.append(name)
    netadpter_box.append(netadpter.Manufacturer)
    netadpter_box.append(netadpter.DeviceID)
    netadpter_box.append(netadpter.AdapterType)
    netadpter_box.append(netadpter.PhysicalAdapter)
    netadpter_box.append(netadpter.NetEnabled)
    netadpter_box.append(netadpter.MACAddress)
    netadapter_info.append(netadpter_box)
    print('>', end='')
    time.sleep(0.1)
netadapter_csv_headers.append('网卡总数：%s' % len(netadapter_info))
print('\n网卡信息获取完毕。\n开始获取网络连接信息')

## 网络连接信息
net_stats = psutil.net_if_stats()
net_addrs = psutil.net_if_addrs()
for key, value in net_stats.items():
    net_box = []
    net_box.append(key)
    net_box.append(value.isup)
    net_box.append('%sMbps' % value.speed)
    net_box.append(net_addrs.get(key)[1].address)
    net_box.append(net_addrs.get(key)[1].netmask)
    netconnect_info.append(net_box)
    print('>', end='')
    time.sleep(0.1)
netconnect_csv_headers.append('可见网络是适配器总数：%s' % len(netconnect_info))
print('\n网络连接信息获取完毕。\n开始获取硬盘信息')

## 硬盘
for disk in w.Win32_DiskDrive():
    disk_info_sub = []
    # disk_info_sub.append(cpu_info[0][0])
    diskSize = int(disk.size)
    disk_info_sub.append(disk.Caption)
    disk_info_sub.append("%.2fGB" % (diskSize / 1024 ** 3))
    disk_info.append(disk_info_sub)
    print('>', end='')
    time.sleep(0.1)
disk_csv_headers.append('硬盘总数：%s' % len(disk_info))
print('\n硬盘信息获取完毕。\n开始获取系统资源占用信息')

## 资源占用
### 主机名
# resource_info.append(cpu_info[0][0])
### 主板型号
for board in w.Win32_baseboard():
    resource_info.append(board.Manufacturer)
    resource_info.append(board.SerialNumber)
    resource_info.append(board.Product)
    print('>', end='')
    time.sleep(0.1)

## BIOS信息
for BIOS in w.Win32_BIOS():
    resource_info.append(BIOS.Manufacturer)
    resource_info.append(BIOS.Name)
    resource_info.append(BIOS.Version)
    resource_info.append(BIOS.SerialNumber)
    print('>', end='')
    time.sleep(0.1)

### CPU占用
cpu_precent = psutil.cpu_percent(interval=None)
resource_info.append(cpu_precent)
print('>', end='')
time.sleep(0.1)

### 内存占用
memory_usage = psutil.virtual_memory()
memory_total = memory_usage.total
memory_available = memory_usage.available
memory_used = memory_usage.used
resource_info.append(str(round(memory_total / 1024 ** 3, 2)) + 'GB')
resource_info.append(str(round(memory_available / 1024 ** 3, 2)) + 'GB')
resource_info.append(str(round(memory_used / 1024 ** 3, 2)) + 'GB')
resource_info.append(time.asctime(time.localtime(time.time())))
print('>', end='')
time.sleep(0.1)

### 分区占用
# partition_info.append(cpu_info[0])
partitions_list = psutil.disk_partitions()
for diskpart in partitions_list:
    partition_box = []
    try:
        partition_box.append(diskpart.mountpoint)
        partition_box.append(diskpart.fstype)
        usage = psutil.disk_usage(diskpart.device)
        partition_box.append('%.2fGB' % (usage.total / 1024 ** 3))
        partition_box.append('%.2fGB' % (usage.used / 1024 ** 3))
        partition_box.append('%.2fGB' % (usage.free / 1024 ** 3))
        partition_box.append('%s%%' % usage.percent)
        partition_info.append(partition_box)
        print('>', end='')
        time.sleep(0.1)
    except Exception as e:
        print(e)
        continue

partitions_csv_header.append('分区总数：%s' % len(partition_info))
print('\n系统资源占用信息获取完毕。\n开始获取进程信息')

## 进程列表

for pid in psutil.pids():
    try:
        process = psutil.Process(pid)
        process_box = []
        process_box.append(pid)
        process_box.append(process.name())
        process_box.append(process.status())
        process_box.append(time.asctime(time.localtime(process.create_time())))
        process_box.append("%s" % round(process.cpu_times().system, 6))
        process_box.append("%s%%" % round(process.memory_percent(), 6))
        # process_box.append(process.memory_info())
        process_box.append(process.num_threads())
        ps_info.append(process_box)
        print('>', end='')
    except Exception as e:
        print(e)
        continue
ps_csv_headers.append('进程总数：%s' % len(ps_info))
print('\n进程信息获取完毕。\n开始生成文件')


############################################################################################
# -------------------------------------- CSV输出 ------------------------------------------##
############################################################################################

filename = "system_info_" + time.strftime("%Y%m%d%H%M%S") + '.csv'
with open(filename, 'w', encoding='UTF-8', newline='')as f:
    f_csv = csv.writer(f)
    print('>', end='')
    f_csv.writerow(cpu_csv_headers)
    f_csv.writerows(cpu_info)
    print('>', end='')
    f_csv.writerow(memory_csv_headers)
    f_csv.writerows(memory_info)
    print('>', end='')
    f_csv.writerow(netadapter_csv_headers)
    f_csv.writerows(netadapter_info)
    print('>', end='')
    f_csv.writerow(netconnect_csv_headers)
    f_csv.writerows(netconnect_info)
    print('>', end='')
    f_csv.writerow(disk_csv_headers)
    f_csv.writerows(disk_info)
    print('>', end='')
    f_csv.writerow(partitions_csv_header)
    f_csv.writerows(partition_info)
    print('>', end='')
    f_csv.writerow(resource_csv_headers)
    f_csv.writerow(resource_info)
    print('>')
    f_csv.writerow(ps_csv_headers)
    f_csv.writerows(ps_info)
    f.close()
    print('—————————————— CSV写入完成~')
#     print('————————划重点： Info文件保存在脚本当前目录 ————————')
#     input("任意按键退出，感谢您的使用~")


##############################################################################################
### -------------------------------------- XLS输出 ------------------------------------------##
##############################################################################################

## xls
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('sheet1')

## CPU信息
row = 0
for i in range(len(cpu_csv_headers)-1, -1, -1):
    worksheet.write(row, i, cpu_csv_headers.pop())
row_sub = len(cpu_info)
colum_sub = len(cpu_info[0])
for i in range(row+row_sub, row, -1):
    cpu_info_box = cpu_info.pop(0)
    for j in range(colum_sub-1, -1, -1):
        worksheet.write(i, j, cpu_info_box.pop())

## 内存信息
row = row + row_sub + 1
for i in range(len(memory_csv_headers)-1, -1, -1):
    worksheet.write(row, i, memory_csv_headers.pop())
row_sub = len(memory_info)
colum_sub = len(memory_info[0])
for i in range(row+row_sub, row, -1):
    memory_info_box = memory_info.pop(0)
    for j in range(colum_sub-1, -1, -1):
        worksheet.write(i, j, memory_info_box.pop())

## 网卡信息
row = row + row_sub + 1
for i in range(len(netadapter_csv_headers)-1, -1, -1):
    worksheet.write(row, i, netadapter_csv_headers.pop())
row_sub = len(netadapter_info)
colum_sub = len(netadapter_info[0])
for i in range(row+row_sub, row, -1):
    netadapter_info_box = netadapter_info.pop(0)
    for j in range(colum_sub-1, -1, -1):
        worksheet.write(i, j, netadapter_info_box.pop())

## 网卡信息
row = row + row_sub + 1
for i in range(len(netconnect_csv_headers)-1, -1, -1):
    worksheet.write(row, i, netconnect_csv_headers.pop())
row_sub = len(netconnect_info)
colum_sub = len(netconnect_info[0])
for i in range(row+row_sub, row, -1):
    netconnect_info_box = netconnect_info.pop(0)
    for j in range(colum_sub-1, -1, -1):
        worksheet.write(i, j, netconnect_info_box.pop())

# ## 磁盘信息
row = row + row_sub + 1
for i in range(len(disk_csv_headers)-1, -1, -1):
    worksheet.write(row, i, disk_csv_headers.pop())
row_sub = len(disk_info)
colum_sub = len(disk_info[0])
for i in range(row+row_sub, row, -1):
    disk_info_box = disk_info.pop(0)
    for j in range(colum_sub-1, -1, -1):
        worksheet.write(i, j, disk_info_box.pop())

# ## 分区信息
row = row + row_sub + 1
for i in range(len(partitions_csv_header)-1, -1, -1):
    worksheet.write(row, i, partitions_csv_header.pop())
row_sub = len(partition_info)
colum_sub = len(partition_info[0])
for i in range(row+row_sub, row, -1):
    partition_info_box = partition_info.pop(0)
    for j in range(colum_sub-1, -1, -1):
        worksheet.write(i, j, partition_info_box.pop())

# ## 系统资源
row = row + row_sub + 1
for i in range(len(resource_csv_headers)-1, -1, -1):
    worksheet.write(row, i, resource_csv_headers.pop())
row = row + 1
for i in range(len(resource_info)-1, -1, -1):
    worksheet.write(row, i, resource_info.pop())

# ## 进程
row = row + 1
for i in range(len(ps_csv_headers)-1, -1, -1):
    worksheet.write(row, i, ps_csv_headers.pop())
row_sub = len(ps_info)
colum_sub = len(ps_info[0])
for i in range(row+row_sub, row, -1):
    ps_info_box = ps_info.pop(0)
    for j in range(colum_sub-1, -1, -1):
        worksheet.write(i, j, ps_info_box.pop())

filename = "system_info_" + time.strftime("%Y%m%d%H%M%S") + '.xls'
workbook.save(filename)

print('—————————————— XLS写入完成~')
print('———————— 划重点： Info文件保存在脚本当前目录 ————————')
input("任意按键退出，感谢您的使用~")

